package com.appbee.core.client.rpcfilter.filters;

import com.appbee.core.client.cache.ClientCache;
import com.appbee.core.client.rpcfilter.RpcFilter;
import com.appbee.core.client.rpcfilter.RpcFilterChain;
import com.appbee.core.client.rpcfilter.callback.FilterCallback;

public class CacheFilter<I, R> implements RpcFilter<I, R>
{
	private ClientCache<I, R> cache;

	public CacheFilter(int cacheTime, int capcity)
	{
		cache = new ClientCache<I, R>(cacheTime, capcity);
	}

	@Override
	public void doFilter(final I input, final FilterCallback<R> callback,
			RpcFilterChain<I, R> chain)
	{
		R r = cache.get(input);
		if (r == null)
		{
			chain.doFilter(input, new FilterCallback<R>()
			{

				@Override
				public void onSuccess(R response)
				{
					cache.put(input, response);
					callback.onSuccess(response);
				}

			});
		}
		else
			callback.onSuccess(r);
	}

}
